<?php

namespace App\Http\Controllers\Api;

// use App\Http\Controllers\Controller;
use App\Models\Course;
use App\Http\Resources\Course as AppCourse;
use App\Models\Resource;
use App\Http\Resources\Resource as AppResource;
use App\Services\AliVodService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CourseController extends Controller
{
    //课程列表
    public function index(Course $course){
        $courses = $course->orderBy('sort','asc')->get();
        return AppCourse::collection($courses);
    }

    // 课程信息-使用非模型注入方式
    public function course($id){
        // $course = Course::find($id);
        $course = Course::with('chapter.resource')->find($id);
        return new AppCourse($course);
    }


    // 课程信息-使用延迟预加载获取
    // public function course(Course $course){
    //     $course->load('chapter');
    //     return new AppCourse($course);
    // }


    // 资源
    public function resource(Course $course, Resource $resource){
        try {
            Log::info('API资源请求开始', [
                'course_id' => $course->id,
                'resource_id' => $resource->id,
                'resource_type' => $resource->type
            ]);
            
            // 预加载章节关系和课程
            $resource->load(['chapter']);
            
            // 确保资源属于该课程
            $resourceBelongsToCourse = false;
            
            // 检查资源是否属于课程的任何章节
            if ($resource->chapter && $resource->chapter->isNotEmpty()) {
                // 如果章节是集合
                foreach ($resource->chapter as $chapter) {
                    if ($chapter->course_id == $course->id) {
                        $resourceBelongsToCourse = true;
                        break;
                    }
                }
            } else if ($resource->chapter && !is_null($resource->chapter->first()) && $resource->chapter->first()->course_id == $course->id) {
                // 如果章节是单个对象
                $resourceBelongsToCourse = true;
            }
            
            Log::info('资源章节关联检查', [
                'course_id' => $course->id,
                'resource_id' => $resource->id,
                'belongs_to_course' => $resourceBelongsToCourse,
                'chapter_type' => gettype($resource->chapter),
                'chapter_count' => is_object($resource->chapter) ? $resource->chapter->count() : 0
            ]);
            
            if (!$resourceBelongsToCourse) {
                Log::warning('API资源不属于指定课程', [
                    'course_id' => $course->id,
                    'resource_id' => $resource->id
                ]);
                
                return response()->json([
                    'code' => 0,
                    'msg' => '该资源不属于指定课程'
                ], 403);
            }
            
            // 预加载视频关联
            if ($resource->type == Resource::VIDEO) {
                $resource->load('video');
                
                // 检查视频是否存在
                if (!$resource->video) {
                    Log::warning('API资源的视频数据不存在', [
                        'resource_id' => $resource->id
                    ]);
                    
                    return response()->json([
                        'code' => 0,
                        'msg' => '该资源的视频数据不存在'
                    ], 404);
                }
                
                Log::info('视频资源加载成功', [
                    'video_id' => $resource->video->id,
                    'ali_id' => $resource->video->ali_id ?? 'null'
                ]);
            } else if ($resource->type == Resource::DOC) {
                $resource->load('doc');
            }
            
            // 使用资源转换器返回结果
            Log::info('API资源请求成功', [
                'course_id' => $course->id,
                'resource_id' => $resource->id
            ]);
            
            return new AppResource($resource);
            
        } catch (\Exception $e) {
            Log::error('API获取资源信息失败', [
                'course_id' => $course->id,
                'resource_id' => $resource->id,
                'error_message' => $e->getMessage(),
                'error_file' => $e->getFile(),
                'error_line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'code' => 0,
                'msg' => '获取资源信息失败: ' . $e->getMessage()
            ], 500);
        }
    }
    
    // 测试视频播放凭证API
    public function testVideoPlayAuth(Request $request) {
        try {
            $videoId = $request->input('videoId');
            
            if (empty($videoId)) {
                return response()->json([
                    'code' => 0,
                    'msg' => '请提供视频ID'
                ]);
            }
            
            // 使用服务获取播放凭证
            $vodService = new AliVodService();
            $playAuth = $vodService->getPlayAuth($videoId);
            
            if (empty($playAuth)) {
                return response()->json([
                    'code' => 0,
                    'msg' => '获取播放凭证失败',
                    'videoId' => $videoId
                ]);
            }
            
            return response()->json([
                'code' => 1,
                'msg' => '获取播放凭证成功',
                'data' => [
                    'VideoId' => $videoId,
                    'PlayAuth' => $playAuth
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('测试播放凭证异常', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'code' => 0,
                'msg' => '测试播放凭证异常: ' . $e->getMessage()
            ]);
        }
    }

    // 测试视频播放地址API
    public function testVideoPlayInfo(Request $request) {
        try {
            $videoId = $request->input('videoId');
            
            if (empty($videoId)) {
                return response()->json([
                    'code' => 0,
                    'msg' => '请提供视频ID'
                ]);
            }
            
            // 使用服务获取播放地址
            $vodService = new AliVodService();
            $playInfo = $vodService->getPlayInfo($videoId, [
                'formats' => 'mp4,m3u8',
                'authTimeout' => 3600,
            ]);
            
            if (empty($playInfo)) {
                return response()->json([
                    'code' => 0,
                    'msg' => '获取播放地址失败',
                    'videoId' => $videoId
                ]);
            }
            
            // 提取可直接播放的URL
            $playUrls = [];
            if (isset($playInfo['PlayInfoList']['PlayInfo']) && is_array($playInfo['PlayInfoList']['PlayInfo'])) {
                foreach ($playInfo['PlayInfoList']['PlayInfo'] as $info) {
                    if (isset($info['PlayURL'])) {
                        $format = $info['Format'] ?? 'unknown';
                        $definition = $info['Definition'] ?? '';
                        $playUrls[$format . '_' . $definition] = $info['PlayURL'];
                    }
                }
            }
            
            // 优先获取m3u8格式的地址
            $directPlayUrl = $playUrls['m3u8_HD'] ?? $playUrls['m3u8_SD'] ?? $playUrls['m3u8_LD'] ?? 
                             ($playUrls['mp4_HD'] ?? $playUrls['mp4_SD'] ?? $playUrls['mp4_LD'] ?? '');
            
            return response()->json([
                'code' => 1,
                'msg' => '获取播放地址成功',
                'data' => [
                    'VideoId' => $videoId,
                    'PlayURLs' => $playUrls,
                    'DirectPlayURL' => $directPlayUrl,
                    'PlayInfo' => $playInfo
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('测试播放地址API异常', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'code' => 0,
                'msg' => '测试播放地址API异常: ' . $e->getMessage()
            ]);
        }
    }
    
    // 搜索课程
    public function search(Request $request) {
        try {
            $keyword = $request->input('keyword');
            
            Log::info('API课程搜索请求开始', [
                'keyword' => $keyword
            ]);
            
            if (empty($keyword)) {
                return response()->json([
                    'code' => 0,
                    'msg' => '请提供搜索关键词'
                ]);
            }
            
            // 搜索课程
            $courses = Course::where('title', 'like', '%' . $keyword . '%')
                ->orWhere('desc', 'like', '%' . $keyword . '%')
                ->orderBy('sort', 'asc')
                ->get();
            
            Log::info('API课程搜索结果', [
                'keyword' => $keyword,
                'count' => $courses->count()
            ]);
            
            if ($courses->isEmpty()) {
                return response()->json([
                    'code' => 1,
                    'msg' => '未找到匹配的课程',
                    'data' => []
                ]);
            }
            
            return response()->json([
                'code' => 1,
                'msg' => '搜索成功',
                'data' => AppCourse::collection($courses)
            ]);
            
        } catch (\Exception $e) {
            Log::error('API课程搜索异常', [
                'error' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 0,
                'msg' => '搜索课程失败: ' . $e->getMessage()
            ], 500);
        }
    }
}
